import { Layout, message } from 'antd';
import { Footer } from 'antd/es/layout/layout';
import React, { type CSSProperties, Suspense, useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet-async';

import FusionContextProvider, { FusionContext } from './context';
import { useContextSelector } from 'use-context-selector';
import { useNavigate } from 'react-router-dom';
import chatService from '@/api/services/chatService';
import fusionService from '@/api/services/fusionService';
import { useDatasetPermit } from '@/store/configStore';
import workbenchService from '@/api/services/workbenchService';
import { AppWorkbenchType } from '@/common/app/constants';
import orchestrationService from '@/api/services/orchestrationService';
import {
  GetWorkBenhList,
  MenuContentType,
  agentSquareType,
  historicalDialogueType,
} from '@/common';
import { CircleLoading } from '@/components/loading';
import useWindowWidth from '@/hooks/event/use-window-width';
import { NAV_COLLAPSED_WIDTH, NAV_WIDTH } from '@/layouts/work-layouts/config';
import { useParams } from '@/router/hooks';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useSettings } from '@/store/settingStore';
import { useResponsive } from '@/theme/hooks';
import { ThemeLayout } from '@/types/enum';

import Header from '../app-qa/components/header';
import Share from '../share';

import Main from './components/Main';
import Nav from './components/Nav';

const Dashboard = React.lazy(() => import('@/pages/report'));
const Chat = React.lazy(() => import('@/pages/app-fusion/components/FusionChat'));
const FusionPublicAgent = React.lazy(() => import('@/pages/app-fusion/view/fusion-public-agent'));
const FusionHistoryChat = React.lazy(() => import('@/pages/app-fusion/view/fusion-history-chat'));
const FusionAllHistoryChat = React.lazy(() => import('@/pages/app-fusion/view/fusion-all-history'));
const FusionSearch = React.lazy(() => import('@/pages/app-fusion/view/fusion-search'));
export default function AppFusion() {
  const {
    appId = '',
    shareId = '',
    isFusionApp,
    isPublic,
    chatId,
  } = useParams() as {
    chatId: string;
    appId: string;
    shareId: string;
    isFusionApp: boolean;
    isPublic: string;
  };
  const {
    setSubAppDetail,
    setFusionAppId,
    setAppDetail,
    setFusionAgentSquare,
    appName,
    appLogo,
    showKeyAgent,
    showkeyHistory,
    setShowkeyHistory,
    setShowKeyAgent,
  } = useOrchestrationStore();
  const { deleteCollect } = useContextSelector(FusionContext, (s) => s);
  const { themeLayout } = useSettings();
  const { screenMap } = useResponsive();
  const { isPc } = useWindowWidth();
  const [contentType, setContentType] = useState<MenuContentType>('homepage');
  const [agentSquare, setAgentSquare] = useState<agentSquareType[]>([]);
  const [historicalDialogue, setHistoricalDialogue] = useState<historicalDialogueType[]>([]);
  // const [dataHistoryDialogue, setDataHistoryDialogue] = useState<historicalDialogueType[]>([]);
  const [isDeleteCollect, setIsDeleteCollect] = useState(false);
  const [isDeleteChatHistory, setIsDeleteChatHistory] = useState<boolean>(false);
  const [fusionChatId, setFusionChatId] = useState<string>('');
  const dataAppId = localStorage.getItem('appId') || '';
  const dataShareId = localStorage.getItem('shareId') || '';

  const [dataId, setDataId] = useState<string[]>([]);
  const [isSearch, setIsSearch] = useState<string | null>(null);
  const [isAuthority, setIsAuthority] = useState<boolean>(false);
  const [isHomePage, setIsHomePage] = useState<boolean | null>(null);
  const [deleteFusionAppId, setDeleteFusionAppId] = useState<string>('');
  const [isLoadingHistory, setIsLoadingHistory] = useState(false);
  const router = useNavigate();
  const datasetPermit = useDatasetPermit();

  const [defaultPage, setDefaultPage] = useState({
    page: 1,
    page_size: 10,
    searchText: '',
    app_type: 'fusion', // 应用类型
    app_workbench_type: 'public', // 应用模板类型
    app_status: null, // 审核状态
  });
  const secondLayoutStyle: CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    background: '#edeff7',
    transition: 'all 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
    paddingLeft:
      isPc && screenMap.md
        ? themeLayout === ThemeLayout.Horizontal
          ? 0
          : themeLayout === ThemeLayout.Mini
          ? NAV_COLLAPSED_WIDTH
          : NAV_WIDTH
        : 0,
  };
  const layoutClassName = useMemo(() => {
    return `bg-[#edeff7] flex h-screen overflow-hidden ${
      themeLayout === ThemeLayout.Horizontal ? 'flex-col' : 'flex-row'
    }`;
  }, [themeLayout]);

  useEffect(() => {
    if (appId != '' && contentType == 'homepage' && !isFusionApp) {
      localStorage.setItem('appId', appId);
      localStorage.setItem('shareId', shareId);
    }
  });

  // 切换导航栏
  const changeContentType = (contentType: MenuContentType) => {
    setContentType(contentType);
    setIsSearch(null);
    setSubAppDetail(null);
    setFusionAppId('');
    if (contentType === 'public-agent') {
      getCollectAgentList();
    }
    if (contentType === 'homepage') {
      // 新建对话 需要删除之前的数据
      setIsHomePage(!isHomePage);
      // router('/fusion?appId=' + dataAppId + '&shareId=' + dataShareId);

      // 新建会话，设置chatId为空
      const params = new URLSearchParams(window.location.search);
      params.set('chatId', '');
      const newUrl = `${window.location.pathname}?${params.toString()}`;
      router(newUrl);
    }
    if (contentType === 'history') {
      getChatHistory();
      setFusionChatId(''); // 清空之前的对话
    }
    if (contentType === 'collect-chat-type') {
      setContentType('homepage');
    }
    if (contentType === 'dashboard') {
      setContentType('dashboard');
    }
  };

  // 获取收藏引用
  const getCollectAgentList = async () => {
    try {
      const res = await fusionService.getCollectAgentListApi({
        fusionAppId: appId,
      });
      setAgentSquare(res && res.slice(0, 5));
      setFusionAgentSquare(res && res.slice(0, 5));
    } catch (error) {
      // message.error('获取收藏失败');
    }
  };
  // 获取对话历史
  const getChatHistory = async () => {
    try {
      const setId: any = [];
      const res = await workbenchService.workListApi(defaultPage);
      res.app_list.forEach((item: any) => {
        setId.push(item.app_id);
      });
      // setId = [dataAppId, ...setId];
      setDataId(setId);
      const today = new Date();
      today.setHours(23, 59, 59, 999);
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setDate(today.getDate() - 7);
      const historyData = await chatService.getHistories({
        // appId: dataAppId == appId ? dataAppId : appId, //传数组
        appId,
        pageNum: 1,
        pageSize: 10,
        dateStart: start.toISOString(),
        dateEnd: today.toISOString(),
        q: '',
        // isFusionApp: true,
        fusionAppId: appId,
        isGlobal: true, // 所有应用true，反之false
      });
      setHistoricalDialogue(historyData?.data || []);
    } catch (error) {
      message.error('获取失败');
    }
  };

  useEffect(() => {
    // 查看收藏应用
    getCollectAgentList();
    // 获取对话历史
    getChatHistory();
    // 获取应用的权限信息
    getAgentAuthority(appId);

    return () => {
      setAppDetail({});
      setSubAppDetail(null);
      setFusionAppId('');
    };
  }, []);

  // 删除导航栏收藏应用
  const deleteCollectAgent = async (event: any, appId: string) => {
    event.stopPropagation();
    try {
      await fusionService.deleteCollectAgentApi({ appId, fusionAppId: dataAppId });
      getCollectAgentList();
      setIsDeleteCollect(!isDeleteCollect);
      message.success('移除收藏');
    } catch (error) {
      message.error('移除失败');
    }
  };
  // 删除历史对话应用
  const deleteHistoryDialogue = async (event: any, item: historicalDialogueType) => {
    event.stopPropagation();
    try {
      await fusionService.deleteChatHistoryApi({
        appId: item.appId,
        chatId: item._id,
      });
      if (!isPc) {
        getChatHistory();
        setIsDeleteChatHistory(!isDeleteChatHistory);
        message.success('删除成功');
        return;
      }
      if (item._id === chatId) {
        // 这里加个判断，相等的对话才更新
        setContentType('homepage');
        setSubAppDetail(null);
      }
      getChatHistory();
      setIsDeleteChatHistory(!isDeleteChatHistory);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 发起获取应用详情
  const getAppDetail = (id: string) => {
    orchestrationService.getAppDetailV2(id, AppWorkbenchType.public).then((app) => {
      setSubAppDetail(app);
    });
  };

  // 收藏应用对话
  const onGetCollect = (item: agentSquareType) => {
    setContentType('homepage');
    orchestrationService.getAppDetailV2(appId, AppWorkbenchType.public).then((data) => {
      setAppDetail(data);
      // setFusionAppId(appId);
      setFusionAppId(item.appId);
      getAppDetail(item.appId);
    });
    // setFusionChatId(item.appId);
    // setSubAppDetail(null);
    // setFusionAppId('');
    //   setContentType('collect-chat');
    // router('/fusion?appId=' + item.appId + '&shareId=' + item.shareId + '&isFusionApp=true');
    // setFusionChatId(item.appId);
  };
  // 融合子应用对话
  const onGetFusionCollect = async (item: GetWorkBenhList) => {
    !isPc && setShowKeyAgent(false);
    setContentType('homepage');
    orchestrationService.getAppDetailV2(appId, AppWorkbenchType.public).then((data) => {
      setAppDetail(data);
      // setFusionAppId(appId);
      setFusionAppId(item.app_id);
      getAppDetail(item.app_id);
    });

    // setFusionChatId(item.app_id);
    // const res = await orchestrationService.getAppDetailV2(item.app_id, AppWorkbenchType.public);
    // if (res.app_id && res.share_id) {
    //   if (isPc) {
    //     router('/fusion?appId=' + res.app_id + '&shareId=' + res.share_id + '&isFusionApp=true');
    //   } else {
    //     router(`/fusion?appId=${res.app_id}&shareId=${res.share_id}&isFusionApp=true`);
    //   }
    //   setContentType('collect-chat');
    //   setFusionChatId(res.app_id);
    // }
  };

  // 历史应用对话
  const onGetHistoryDialogue = async (item: historicalDialogueType) => {
    setSubAppDetail(null);
    setFusionAppId('');
    // 获取本地appId
    router(`/fusion?appId=${dataAppId}&shareId=${dataShareId}&isFusionApp=true`);
    setContentType('history-chat');
    setFusionChatId(item._id);
    getAgentAuthority(item.appId);
    setDeleteFusionAppId(item.appId);
  };
  const handleChatItemClick = (item: historicalDialogueType) => {
    // 获取本地appId
    const isPublicFlag = isPublic == 'true';
    let url = `/fusion?appId=${dataAppId}&shareId=${dataShareId}&isFusionApp=true`;
    if (isPublicFlag === true) {
      url += `&isPublic=true`;
    }
    router(url);
    setContentType('history-chat');
    setFusionChatId(item._id);
    getAgentAuthority(item.appId);
    setDeleteFusionAppId(item.appId);
  };

  // 获取应用的对话权限
  const getAgentAuthority = async (appId: string) => {
    try {
      // const res = await fusionService.getAuthorityApi({ appId });
      // setIsAuthority(res.isAuthority);
      setIsAuthority(true);
      // if (contentType === 'homepage' && !res.isAuthority) {
      //   router('/404');
      // }
      // if (contentType === 'homepage' && !res.isFusionapp) {
      //   message.error('您的应用不是融合应用');
      //   router('/worklayouts/');
      // }
    } catch (error) {
      message.error('权限获取失败');
    }
  };

  // 加载历史对话  对话的时候加载
  const onUpdateHistory = () => {
    // getChatHistory();
    setIsLoadingHistory(!isLoadingHistory);
  };
  // 删除当前 对话
  const deleteCollectChat = async () => {
    let collectChatId = '';
    let id = '';
    if (contentType == 'chat') {
      collectChatId = historicalDialogue[0]._id;
      id = historicalDialogue[0].appId;
    } else {
      collectChatId = fusionChatId;
      id = deleteFusionAppId;
    }
    try {
      await fusionService.deleteChatHistoryApi({
        appId: id,
        chatId: collectChatId,
      });
      getChatHistory();
      setIsDeleteChatHistory(!isDeleteChatHistory);
      setContentType('homepage');
      setIsHomePage(!isHomePage);
      setSubAppDetail(null);
      setFusionAppId('');
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };
  const cancel = () => {
    setIsSearch(null);
  };
  const changeSearchValue = (value: string) => {
    setIsSearch(value);

    if (!value.trim()) return;
    const existingHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');
    const updatedHistory = [
      value,
      ...existingHistory.filter((item: string) => item !== value),
    ].slice(0, 20);
    localStorage.setItem('searchHistory', JSON.stringify(updatedHistory));
  };
  const onClickText = (value: string) => {
    setIsSearch(value);
  };

  const contentTypeFun = () => {
    if (contentType === 'dashboard') {
      return <Dashboard />;
    }
    if (contentType === 'homepage') {
      return (
        <Chat
          contentType={contentType}
          isDeleteChatHistory={isDeleteChatHistory}
          onUpdateHistory={onUpdateHistory}
          changeContentType={changeContentType}
          deleteCollectChat={deleteCollectChat}
          setContentType={setContentType}
          isHomePage={isHomePage}
        />
      );
    }
    if (contentType === 'public-agent') {
      return (
        <FusionPublicAgent
          onChangeCollect={getCollectAgentList}
          onGetFusionCollect={onGetFusionCollect}
          isDeleteCollect={isDeleteCollect}
          isSearch={isSearch}
          contentType={contentType}
        />
      );
    }
    if (contentType === 'history') {
      return (
        <FusionHistoryChat
          handleChatItemClick={handleChatItemClick}
          deleteHistoryDialogue={deleteHistoryDialogue}
          setContentType={setContentType}
          isSearch={isSearch}
          isDeleteChatHistory={isDeleteChatHistory}
          dataId={dataId}
        />
      );
    }
    if (contentType === 'search') {
      return <FusionSearch onClickText={onClickText} />;
    }
    if (contentType !== null) {
      return (
        <Chat
          fusionChatId={fusionChatId}
          contentType={contentType}
          isDeleteChatHistory={isDeleteChatHistory}
          onUpdateHistory={onUpdateHistory}
          changeContentType={changeContentType}
          deleteCollectChat={deleteCollectChat}
          setContentType={setContentType}
          isAuthority={isAuthority}
          isHomePage={isHomePage}
        />
      );
    }

    if (contentType === 'share') {
      return <Share />;
    }
    return <div />;
  };

  return (
    <div>
      <FusionContextProvider>
        <Layout className={layoutClassName}>
          {/* <Helmet>
            <title>天工睿核智能体</title>
            <link rel="icon" href="/favicon.ico"></link>
          </Helmet> */}
          <Helmet>
            <title>{appName || ''}</title>
            {/* <link rel="icon" href={appLogo ? `${appLogo}?v=${Date.now()}` : ''} className='rounded-[50%]' /> */}
            <link rel="icon" href={appLogo} className="rounded-[50%]" />
          </Helmet>
          <Suspense fallback={<CircleLoading />}>
            <Layout
              className={`flex ${isPc ? '!bg-[#FFFFFF]' : '!bg-[#FFFFFF]'}`}
              style={isPc ? {} : secondLayoutStyle}
            >
              {(themeLayout === ThemeLayout.Vertical || themeLayout === ThemeLayout.Mini) &&
              isPc ? (
                <Header
                  currentView={contentType as string}
                  onHistoryClick={() => {
                    setShowkeyHistory(!showkeyHistory);
                  }}
                  onHomeClick={() => {
                    changeContentType('homepage');
                  }}
                />
              ) : (
                contentType !== 'history' &&
                !showKeyAgent &&
                !showkeyHistory && (
                  <Header
                    currentView={contentType as string}
                    onHistoryClick={() => {
                      changeContentType('history');
                    }}
                    onHomeClick={() => {
                      changeContentType('homepage');
                    }}
                    onDashboardClick={() => {
                      changeContentType('dashboard');
                    }}
                    onFusionAppClick={() => {
                      setShowKeyAgent(true);
                    }}
                  />
                )
              )}
              <Main
                contentTypeFun={contentTypeFun}
                onChangeCollect={getCollectAgentList}
                onGetFusionCollect={onGetFusionCollect}
                isDeleteCollect={isDeleteCollect}
                isSearch={isSearch}
                contentType={contentType}
                handleChatItemClick={handleChatItemClick}
                deleteHistoryDialogue={deleteHistoryDialogue}
                isLoadingHistory={isLoadingHistory}
                isDeleteChatHistory={isDeleteChatHistory}
                dataId={dataId}
              />
              <Footer style={{ padding: '0px' }}>
                <div>
                  {' '}
                  {themeLayout === ThemeLayout.Horizontal && (
                    <Nav
                      changeContentType={changeContentType}
                      deleteCollectAgent={deleteCollectAgent}
                      deleteHistoryDialogue={deleteHistoryDialogue}
                      onGetCollect={onGetCollect}
                      onGetHistoryDialogue={onGetHistoryDialogue}
                      agentSquare={agentSquare}
                      contentType={contentType}
                      historicalDialogue={historicalDialogue}
                    />
                  )}
                </div>
              </Footer>
            </Layout>
          </Suspense>
        </Layout>
      </FusionContextProvider>
    </div>
  );
}
